<?php

declare(strict_types=1);

namespace App\Controller\Admin\V1\Order;

use App\Constants\Order\SchoolMasterOrderCode;
use App\Controller\Admin\V1\Controllers;
use App\Exception\InternalException;
use App\Services\Order\SchoolMasterOrder as SchoolMasterOrderServices;
use App\Request\Order\SchoolMasterOrder as SchoolMasterOrderRequest;
use App\Utils\Other\Office\Excel\Export;
use App\Utils\Other\Office\Excel\Import;
use Hyperf\DbConnection\Db;
use function Hyperf\Translation\__;

class Delivery extends Controllers
{
    /**
     * 请求类
     * @var string
     */
    protected string $requestClass = SchoolMasterOrderRequest::class;

    /**
     * 快递公司
     * @var array|string[]
     */
    protected array $express = [
        'STO' => '申通',
        'SFEXPRESS' => '顺丰',
        'ZTO' => '中通',
        'YUNDA' => '韵达',
        'YTO' => '圆通'
    ];

    public function __construct(
        SchoolMasterOrderServices $schoolMasterOrderServices
    )
    {
        parent::__construct();
        $this->services = $schoolMasterOrderServices;
    }

    /**
     * 订单发货模板
     * @param Export $export
     * @return \Psr\Http\Message\ResponseInterface|void
     * @throws \PhpOffice\PhpSpreadsheet\Exception
     * @throws \PhpOffice\PhpSpreadsheet\Writer\Exception
     */
    public function demo(Export $export)
    {
        $body = [];
        foreach ($this->express as $key => $express) {
            $body[] = [
                $key,
                $express
            ];
        }

        return $export->init('订单发货模板,红色为必填项')
            ->setWidth(30)
            ->setTitle(['订单编号', '运单号', '物流公司编码'])
            ->setCellType(['A', 'B'])
            ->setFill(['A1', 'B1', 'C1'], 'FF0000')
            ->setActiveSheetIndex(1, true, '物流公司编码')
            ->setTitle(['物流公司编码', '物流公司名称'])
            ->setBody($body)
            ->setActiveSheetIndex(0, false)
            ->download('订单发货模板');
    }

    /**
     * 发货
     * @param Import $import
     */
    public function import(Import $import)
    {
        $file = $this->files('file');

        $validate = [
            'C' => function ($item, $data) {
                if (!isset($this->express[$item])) {
                    return __('validation.in_array', [
                        'attribute' => 'C',
                        'other' => implode(',', array_keys($this->express))
                    ]);
                }
                return true;
            }
        ];

        $data = $import->reader($file)
            ->getData(0, true, ['订单编号' => 'A', '运单号' => 'B', '物流公司编码' => 'C'], $validate);

        $orderModels = $this->services
            ->where('type', SchoolMasterOrderCode::TYPE_SNACK_SHOP)
            ->where('pay_status', SchoolMasterOrderCode::PAY_STATUS_PAID)
            ->where('status', SchoolMasterOrderCode::STATUS_PICKING_UP)
            ->whereIn('no', array_column($data, 'A'))
            ->cursor();

        Db::transaction(function () use ($orderModels, $data) {
            foreach ($orderModels as $orderModel) {
                $row = array_search($orderModel->no, array_column($data, 'A')) + 2;
                if (!$orderModel->fill([
                    'express_no' => $data[$row]['B'],
                    'express_code' => $data[$row]['C'],
                    'express_name' => $this->express[$data[$row]['C']],
                    'status' => SchoolMasterOrderCode::STATUS_DELIVERY_PENDING
                ])->save()) {
                    throw new InternalException();
                }
            }
        });

        return updated();
    }
}
